package cn.lcfms.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


import net.sf.json.JSON;

public class HttpUtils {
	/**
	 * 使用GET方法从WEB上获取信息，并将数据保存到一个字节数组中
	 * 
	 * @param urlpath
	 *            url地址
	 * @return 字节数组
	 * @throws IOException 
	 * @throws  
	 * @throws Exception
	 */
	public static String getdata(String urlpath) throws IOException{
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 基于HTTP连接的一个对象
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			BufferedInputStream buffer = new BufferedInputStream(inputStream);
			byte[] data = HttpUtils.stream_to_byte(buffer);
			inputStream.close();
			return new String(data, "utf-8");
		}
		return null;
	}
	
	/**
	 * 使用GET方法从WEB上获取信息，并将数据保存到一个字节数组中
	 * 
	 * @param urlpath
	 *            url地址
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] getDataByte(String urlpath) throws IOException {
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 基于HTTP连接的一个对象
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			BufferedInputStream buffer = new BufferedInputStream(inputStream);
			byte[] data = HttpUtils.stream_to_byte(buffer);
			inputStream.close();
			return data;
		}
		return new byte[0];
	}

	/**
	 * 模拟浏览器使用GET方法从WEB上获取信息，并将数据保存到一个字节数组中
	 * 
	 * @param urlpath
	 *            url地址
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] browser(String urlpath,String cookie) throws IOException {
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		if(cookie!=null && !cookie.equals("")) {
			conn.setRequestProperty("Cookie", cookie);
		}	
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			BufferedInputStream buffer = new BufferedInputStream(inputStream);
			byte[] data = HttpUtils.stream_to_byte(buffer);
			inputStream.close();
			return data;
		}
		return new byte[0];
	}

	/**
	 * 从POST方法向WEB发送数据,并返回一段字符串
	 * 
	 * @param map
	 *            将要发送的参数，键位KEY，值为VALUE
	 * @param url
	 *            url地址
	 * @return
	 * @throws IOException 
	 * @throws Exception
	 */
	public static String postData(Map<String, Object> map, String url) throws IOException{
		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		StringBuffer params = new StringBuffer();
		for (String key : map.keySet()) {
			Object val = map.get(key);
			val = URLEncoder.encode(String.valueOf(map.get(key)), "utf-8");
			params.append(key).append("=").append(val).append("&");
		}
		byte[] data = params.substring(0, params.length() - 1).getBytes();
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
		if (conn.getResponseCode() == 200) {
			InputStream stream = conn.getInputStream();
			byte[] data_r = HttpUtils.stream_to_byte(stream);
			return new String(data_r, "utf-8");
		} else {
			return "";
		}
	}

	
	public static String postJson(JSON json, String url) throws Exception {
		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/json");
		byte[] bs = json.toString().getBytes("utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(bs.length));
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(bs);
		outputStream.flush();
		outputStream.close();
		if (conn.getResponseCode() == 200) {
			InputStream stream = conn.getInputStream();
			byte[] data_r = HttpUtils.stream_to_byte(stream);
			return new String(data_r, "utf-8");
		} else {
			return "";
		}
	}

	
	public static String postXml(String json, String url) throws Exception {
		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/xml");
		byte[] bs = json.getBytes("utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(bs.length));
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(bs);
		outputStream.flush();
		outputStream.close();
		if (conn.getResponseCode() == 200) {
			InputStream stream = conn.getInputStream();
			byte[] data_r = HttpUtils.stream_to_byte(stream);
			return new String(data_r, "utf-8");
		} else {
			return "";
		}
	}

	
	public static String postByte(byte[] data, String url,String contentType) throws Exception {
		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", contentType);
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
		if (conn.getResponseCode() == 200) {
			InputStream stream = conn.getInputStream();
			byte[] data_r = HttpUtils.stream_to_byte(stream);
			return new String(data_r, "utf-8");
		} else {
			return "";
		}
	}

	/*
	 * 将一个输入流转换成字节数组
	 */
	private static byte[] stream_to_byte(InputStream stream) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] bs = new byte[1024];
		int len = -1;
		try {
			while ((len = stream.read(bs)) != -1) {
				bos.write(bs, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] b = bos.toByteArray();
		try {
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
}
